package com.baidu.acg.industry.bigdata.service;

import com.baidu.acg.industry.bigdata.model.PodTemplate;
import io.kubernetes.client.custom.IntOrString;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Container;
import io.kubernetes.client.openapi.models.V1ContainerPort;
import io.kubernetes.client.openapi.models.V1HostPathVolumeSource;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodSpec;
import io.kubernetes.client.openapi.models.V1Service;
import io.kubernetes.client.openapi.models.V1ServicePort;
import io.kubernetes.client.openapi.models.V1ServiceSpec;
import io.kubernetes.client.openapi.models.V1Status;
import io.kubernetes.client.openapi.models.V1Volume;
import io.kubernetes.client.openapi.models.V1VolumeMount;
import io.kubernetes.client.util.Config;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class K8sDeployer {

//    public static void main(String[] args) throws Exception {
//        System.setProperty("https.protocols", "TLSv1.2");
//        System.setProperty("jdk.tls.client.protocols", "TLSv1.2");
//
//        ApiClient client = Config.defaultClient();
//        Configuration.setDefaultApiClient(client);
//        CoreV1Api coreApi = new CoreV1Api();
////
////        createConfigMap(coreApi);
////        createPod(coreApi);
////        createService(coreApi);
//
////        deleteK8sService();
////        createK8sPod();
//    }

    public void createK8sPod(PodTemplate podTemplate) {
        System.setProperty("https.protocols", "TLSv1.2");
        System.setProperty("jdk.tls.client.protocols", "TLSv1.2");
        try {
            // 在 Pod 内部使用集群内配置（自动加载 ServiceAccount 凭证）
            ApiClient client = Config.defaultClient();
            Configuration.setDefaultApiClient(client);
            CoreV1Api coreApi = new CoreV1Api();

            // 创建资源
            createPod(coreApi, podTemplate);
            createService(coreApi);
        } catch (Exception e) {
            log.error("Failed to create Kubernetes resources", e);
        }

    }


    private void createPod(CoreV1Api api, PodTemplate podTemplate) throws Exception {
        // 宿主机配置文件目录卷（直接映射到容器配置路径）
        V1Volume hostConfigVolume = new V1Volume()
                .name("host-config-volume")
                .hostPath(new V1HostPathVolumeSource()
                        .path(podTemplate.getHostPath()) // 修改为宿主机配置目录
                        .type("DirectoryOrCreate"));
        // 挂载配置
        V1VolumeMount hostConfigMount = new V1VolumeMount()
                .mountPath(podTemplate.getContainerPath()) // 直接映射到容器配置目录
                .name("host-config-volume");

        // 创建 Pod
        V1Pod pod = new V1Pod()
                .metadata(new V1ObjectMeta()
                        .name(podTemplate.getPodName())
                        .labels(Map.of("app", podTemplate.getPodName())))
                .spec(new V1PodSpec()
                        .volumes(Arrays.asList(
                                hostConfigVolume))
                        .containers(Collections.singletonList(
                                new V1Container()
                                        .name("app-container")
                                        .image(podTemplate.getPodImage())
                                        .volumeMounts(Arrays.asList(
                                                hostConfigMount))
                                        // 简化后的启动命令
                                        .command(Arrays.asList("java", "-jar", "/home/hst_asim/datacovert/zhongche-datacovert-api-1.0.0-SNAPSHOT.jar"))
                                        .ports(Collections.singletonList(
                                                new V1ContainerPort().containerPort(8089)
                                        ))
                        )));

        try {
            api.createNamespacedPod(podTemplate.getNameSpace(), pod, null, null, null, null);
            System.out.println("Pod created");
        } catch (Exception e) {
            log.error("create pod error", (Object) e);
            e.printStackTrace();
        }
    }

    private void createService(CoreV1Api api) throws Exception {
        V1Service service = new V1Service()
                .metadata(new V1ObjectMeta().name("zhongche-ceshi-service"))
                .spec(new V1ServiceSpec()
                        .selector(Map.of("app", "zhongche-ceshi-pod"))
                        .ports(Collections.singletonList(
                                new V1ServicePort()
                                        .port(8081)              // Service端口
                                        .targetPort(new IntOrString(8089)) // 必须与容器端口一致
                                        .nodePort(30018)       // 显式指定NodePort
                                        .protocol("TCP")
                        ))
                        .type("NodePort"));

        try {
            api.createNamespacedService("hst-asim", service, null, null, null, null);
            System.out.println("Service created");

        } catch (Exception e) {
            log.error("create service error", e.getCause().getMessage());
            e.printStackTrace();
        }
    }


    private static void deleteConfigMap(CoreV1Api api) {
        try {
            V1Status result = api.deleteNamespacedConfigMap(
                    "app-config",         // ConfigMap名称
                    "default",            // 命名空间
                    null,                 // 优雅删除时间（秒）
                    null,          // V1DeleteOptions
                    null,          // V1DeleteOptions
                    null,           // V1DeleteOptions
                    null,           // V1DeleteOptions
                    null             // V1DeleteOptions
            );
            System.out.println("ConfigMap deleted");
        } catch (ApiException e) {
            if (e.getCode() == 404) {
                System.out.println("ConfigMap not found, skipping deletion");
            } else {
                e.printStackTrace();
            }
        }
    }


    public static void deleteK8sService() throws IOException {
        ApiClient client = Config.defaultClient();
        Configuration.setDefaultApiClient(client);
        CoreV1Api coreApi = new CoreV1Api();
        deletePod(coreApi);
        deleteService(coreApi);
        deleteConfigMap(coreApi);
    }

    private static void deletePod(CoreV1Api api) {
        try {
            V1Pod result = api.deleteNamespacedPod(
                    "java-app",           // Pod名称
                    "default",            // 命名空间
                    null,                 // 优雅删除时间（秒）
                    null,                // 是否干运行
                    null,        // 传播策略（阻塞直到删除完成）
                    null,               // V1DeleteOptions
                    null,               // V1DeleteOptions
                    null                // V1DeleteOptions
            );
            System.out.println("Pod deleted");
        } catch (ApiException e) {
            if (e.getCode() == 404) {
                System.out.println("Pod not found, skipping deletion");
            } else {
                e.printStackTrace();
            }
        }
    }

    private static void deleteService(CoreV1Api api) {
        try {
            V1Service result = api.deleteNamespacedService(
                    "java-service",       // Service名称
                    "default",            // 命名空间
                    null,                 // 优雅删除时间（秒）
                    null,                // 是否干运行
                    null,                // 传播策略
                    null,                // V1DeleteOptions
                    null,                // V1DeleteOptions
                    null                 // V1DeleteOptions
            );
            System.out.println("Service deleted");
        } catch (ApiException e) {
            if (e.getCode() == 404) {
                System.out.println("Service not found, skipping deletion");
            } else {
                e.printStackTrace();
            }
        }
    }

}